function img_preview(img,indeks){
    var src = img.src;
    curr_image = indeks;
    is_preview = true;
    preview_show(src);  
}

function preview_show(src){
    var obj_bg = $('#img-preview-bg');
    var obj_con = $('#img-preview-con');
    var obj_wrap = $('#img-preview-wrap');
    var obj_img = $('#img-preview-img');
    var obj_bottom = $('#img-preview-bottom');
    var obj_close = $('#img-preview-close');
    
    obj_con.fadeIn();
    obj_bg.fadeIn();
    obj_img.hide();
    obj_close.hide();
    
    obj_img.attr('src','');    
    obj_img.attr('src',src);
    var height = obj_img.height();
    var width = obj_img.width();
    var margin_left = width / 2 * (-1);
    var margin_top = height / 2 * (-1);
    
    obj_wrap.animate({
        left: margin_left,
        top: margin_top,
        width: width,
        height: height
    }, 500, function(){
        obj_bottom.height(height + 20);
        obj_bottom.width(width + 20);
        obj_img.fadeIn();
        obj_close.fadeIn();
    });
}

function preview_close(){
    $('#img-preview-bg').fadeOut();
    $('#img-preview-con').fadeOut();
    is_preview = false;
}

function preview_next(){
    var indeks = (curr_image + 1) % total_image;
    slide_preview(indeks);
}

function slide_preview(indeks){
    curr_image = indeks;
    obj = $('#pv-gallery-thumb-' + indeks);
    $(document.documentElement).focus();
    preview_show(obj.attr('src'));
}

var curr_image = 0;
var is_preview = false;

$(document).ready(function(){
    $(document.documentElement).keyup(function(event){
        var indeks;
        if (event.keyCode == 37) { 
            //left
            if(curr_image == 0){
                indeks = total_image - 1;
            } else {
                indeks = curr_image - 1;
            }
            slide_preview(indeks);
        } else if (event.keyCode == 39){
            //right
            indeks = (curr_image + 1) % total_image;
            slide_preview(indeks);
        } else if (event.keyCode == 27){
            //ESC
            preview_close();
        }
    });
});